import React, { useEffect, useState } from 'react';
import { Row, Col, Card, Statistic, List, Typography, Tag, Space, Button } from 'antd';
import {
  UserOutlined,
  CloudDownloadOutlined,
  UploadOutlined,
  DownloadOutlined,
  FireOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { getTorrents } from '../api/torrent';
import { getAdminStats } from '../api/admin';
import { getPublicStats, PublicStats } from '../api/public';
import { Torrent, AdminStats } from '../types';
import { formatBytes, formatDateTime } from '../utils/format';
import CheckinCard from '../components/CheckinCard';
import PermissionGuard from '../components/PermissionGuard';
import { useAuth } from '../context/AuthContext';

const { Title, Text } = Typography;

const Home: React.FC = () => {
  const { isAdmin } = useAuth();
  const [adminStats, setAdminStats] = useState<AdminStats | null>(null);
  const [publicStats, setPublicStats] = useState<PublicStats | null>(null);
  const [latestTorrents, setLatestTorrents] = useState<Torrent[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    console.log('=== Home页面开始获取数据 ===');
    console.log('请求的baseURL:', process.env.REACT_APP_API_URL || '/api');
    
    try {
      setLoading(true);
      
      // 根据用户权限获取不同的统计数据
      if (isAdmin()) {
        console.log('用户是管理员，获取管理员统计数据...');
        try {
          console.log('开始调用getAdminStats...');
          const statsResponse = await getAdminStats();
          console.log('管理员统计数据响应:', statsResponse);
          if (statsResponse.code === 200) {
            setAdminStats(statsResponse.data);
          }
        } catch (error: any) {
          console.error('获取管理员统计数据失败:', error);
          console.error('错误详情:', error.response?.data || error.message);
        }
      } else {
        console.log('用户是普通用户，获取公共统计数据...');
        try {
          console.log('开始调用getPublicStats...');
          const statsResponse = await getPublicStats();
          console.log('公共统计数据响应:', statsResponse);
          if (statsResponse.code === 200) {
            setPublicStats(statsResponse.data);
          }
        } catch (error: any) {
          console.error('获取公共统计数据失败:', error);
          console.error('错误详情:', error.response?.data || error.message);
        }
      }

      // 获取最新种子
      console.log('获取最新种子列表...');
      try {
        console.log('开始调用getTorrents...');
        const torrentsResponse = await getTorrents({ page: 1, size: 10 });
        console.log('种子列表响应:', torrentsResponse);
        if (torrentsResponse.code === 200) {
          setLatestTorrents(torrentsResponse.data.records || []);
        }
      } catch (error: any) {
        console.error('获取种子列表失败:', error);
        console.error('错误详情:', error.response?.data || error.message);
      }
    } catch (error: any) {
      console.error('获取数据失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
    } finally {
      setLoading(false);
      console.log('=== Home页面数据获取完成 ===');
    }
  };

  const getPromotionTag = (promotionStatus: number) => {
    switch (promotionStatus) {
      case 1:
        return <Tag color="green">免费</Tag>;
      case 2:
        return <Tag color="blue">2x上传</Tag>;
      case 3:
        return <Tag color="red">2x下载</Tag>;
      case 4:
        return <Tag color="purple">50%下载</Tag>;
      default:
        return null;
    }
  };

  return (
    <div>
      <Title level={2}>
        <FireOutlined /> 欢迎来到PT站点
      </Title>
      
      <Text type="secondary" style={{ fontSize: 16, display: 'block', marginBottom: 24 }}>
        这里是一个私有的BitTorrent分享社区，致力于高质量资源的分享与交流
      </Text>

      {/* 管理员统计 */}
      <PermissionGuard requireAdmin>
        {adminStats && (
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="总用户数"
                  value={adminStats.totalUsers}
                  prefix={<UserOutlined />}
                  valueStyle={{ color: '#3f8600' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="活跃用户"
                  value={adminStats.activeUsers}
                  prefix={<UserOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="种子总数"
                  value={adminStats.totalTorrents}
                  prefix={<CloudDownloadOutlined />}
                  valueStyle={{ color: '#722ed1' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="在线Peers"
                  value={adminStats.onlinePeers}
                  prefix={<DownloadOutlined />}
                  valueStyle={{ color: '#eb2f96' }}
                />
              </Card>
            </Col>
          </Row>
        )}
      </PermissionGuard>

      {/* 普通用户统计 */}
      {!isAdmin() && publicStats && (
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={12}>
            <Card>
              <Statistic
                title="注册用户数"
                value={publicStats.totalUsers}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#3f8600' }}
              />
            </Card>
          </Col>
          <Col span={12}>
            <Card>
              <Statistic
                title="种子总数"
                value={publicStats.totalTorrents}
                prefix={<CloudDownloadOutlined />}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
        </Row>
      )}

      {/* 快捷操作和签到 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card
            hoverable
            style={{ textAlign: 'center' }}
            styles={{ body: { padding: '40px 24px' } }}
          >
            <CloudDownloadOutlined style={{ fontSize: 48, color: '#1890ff', marginBottom: 16 }} />
            <Title level={4}>浏览种子</Title>
            <Text type="secondary">发现和下载高质量资源</Text>
            <div style={{ marginTop: 16 }}>
              <Link to="/torrents">
                <Button type="primary">立即浏览</Button>
              </Link>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card
            hoverable
            style={{ textAlign: 'center' }}
            styles={{ body: { padding: '40px 24px' } }}
          >
            <UploadOutlined style={{ fontSize: 48, color: '#52c41a', marginBottom: 16 }} />
            <Title level={4}>上传种子</Title>
            <Text type="secondary">分享您的优质资源</Text>
            <div style={{ marginTop: 16 }}>
              <Link to="/upload">
                <Button type="primary">开始上传</Button>
              </Link>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card
            hoverable
            style={{ textAlign: 'center' }}
            styles={{ body: { padding: '40px 24px' } }}
          >
            <FireOutlined style={{ fontSize: 48, color: '#fa8c16', marginBottom: 16 }} />
            <Title level={4}>论坛交流</Title>
            <Text type="secondary">与社区成员互动交流</Text>
            <div style={{ marginTop: 16 }}>
              <Link to="/forum">
                <Button type="primary">进入论坛</Button>
              </Link>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <CheckinCard />
        </Col>
      </Row>

      {/* 最新种子 */}
      <Card
        title={
          <Space>
            <ClockCircleOutlined />
            <span>最新种子</span>
          </Space>
        }
        extra={<Link to="/torrents">查看更多</Link>}
        loading={loading}
      >
        <List
          itemLayout="horizontal"
          dataSource={latestTorrents}
          renderItem={(item) => (
            <List.Item
              actions={[
                <Space key="stats">
                  <Text type="secondary">↑{item.seeders}</Text>
                  <Text type="secondary">↓{item.leechers}</Text>
                  <Text type="secondary">{formatBytes(item.fileSize || item.size || 0)}</Text>
                </Space>
              ]}
            >
              <List.Item.Meta
                title={
                  <Space>
                    <Link to={`/torrents/${item.id}`}>{item.title}</Link>
                    {item.promotionStatus !== undefined && getPromotionTag(item.promotionStatus)}
                  </Space>
                }
                description={
                  <Space split={<span>•</span>}>
                    <Text type="secondary">{item.category}</Text>
                    <Text type="secondary">上传者: {item.uploader || item.uploaderName}</Text>
                    <Text type="secondary">{formatDateTime(item.createdTime || item.uploadedAt || '')}</Text>
                  </Space>
                }
              />
            </List.Item>
          )}
        />
      </Card>
    </div>
  );
};

export default Home; 